<template>
  <div class="pay">
    <van-nav-bar fixed title="订单结算台" left-arrow @click-left="$router.go(-1)" />

    <!-- 地址相关 -->
    <div class="address" @click="showAddress = true,selectAddress()">

      <div class="left-icon">
        <van-icon name="logistics" />
      </div>

      <div class="info" v-if="address !== null">
        <div class="info-content">
          <span class="name">{{ address.name }}</span>
          <span class="mobile">{{ address.tel }}</span>
        </div>
        <div class="info-address">
          {{address.address}}
        </div>
        <div class="info-address">
          {{address.detail}}
        </div>
      </div>

      <div class="info" v-else>
        请选择配送地址
      </div>

      <div class="right-icon">
        <van-icon name="arrow" />
      </div>
    </div>

    <!-- 订单明细 -->
    <div class="pay-list">
      <div class="list">
        <div class="goods-item" v-for="item in orderList" :key="item.id">
            <div class="left">
              <img :src="item.showPicUrl" alt="" />
            </div>
            <div class="right">
              <p class="tit text-ellipsis-2">
                 {{ item.title }}
              </p>
              <p class="info">
                <span class="count">x{{ item.quantity }}</span>
                <span class="price">¥{{ item.quantity * item.price }}</span>
              </p>
            </div>
        </div>
      </div>

      <div class="flow-num-box">
        <span>共 {{ totalCount }} 件商品，合计：</span>
        <span class="money">￥{{ totalPrice }}</span>
      </div>

      <div class="pay-detail">
        <div class="pay-cell">
          <span>订单总金额：</span>
          <span class="red">￥{{ totalPrice }}</span>
        </div>

        <div class="pay-cell">
          <span>优惠券：</span>
          <span>无优惠券可用</span>
        </div>

        <div class="pay-cell">
          <span>配送费用：</span>
          <span v-if="address === null">请先选择配送地址</span>
          <span v-else class="red">+￥0.00</span>
        </div>
      </div>

      <!-- 支付方式 -->
      <div class="pay-way">
        <span class="tit">支付方式</span>
        <div class="pay-cell">
          <span><van-icon name="balance-o" />余额支付（可用 ¥ {{ balance }} 元）</span>
          <!-- <span>请先选择配送地址</span> -->
          <span class="red"><van-icon name="passed" /></span>
        </div>
      </div>

      <!-- 买家留言 -->
      <div class="buytips">
        <textarea placeholder="选填：买家留言（50字内）" name="" id="" cols="30" rows="10" v-model="tips"></textarea>
      </div>
    </div>

    <!-- 底部提交 -->
    <div class="footer-fixed">
      <div class="left">实付款：<span>￥{{ totalPrice }}</span></div>
      <div class="tipsbtn" @click="submit">提交订单</div>
    </div>

    <div class="payKeyboard">
      <van-popup v-model="showKeyboard" round closeable  position="bottom" :style="{ height: '80%' }" @close="handleClose">
        <div class="top_pay">
          <h3>请输入支付密码</h3>
          <span>￥{{ totalPrice }}</span>
        </div>
        <div class="account_pay">
          <div class="left_account">账号</div>
          <div class="right_accountNum">158****1751</div>
        </div>
        <div class="pay_methods">
          <van-radio-group v-model="radio">
            <van-cell-group>
              <van-cell title="余额支付" clickable @click="radio = '1'">
                <template #right-icon>
                  <van-radio name="1" />
                </template>
              </van-cell>
            </van-cell-group>
          </van-radio-group>
        </div>
        <div class="footer_pay">
          <div class="pay_input">
            <div class="input_item" v-for="(item,index) in passwordNums" :key="index">
              <span class="num" v-if="passwordInput.length >= index + 1">*</span>
            </div>
          </div>
          <div class="keyboard_pay">
            <ul>
              <li v-for="(item,index) in keys" :key="index" @click="inputPay(item)">{{ item }}</li>
              <li><van-icon name="revoke" @click="delPay"/></li>
            </ul>
          </div>
        </div>
      </van-popup>
    </div>

    <van-popup v-model="showAddress" position="bottom" closeable round :style="{ 'max-height':'70%' }" @close="changeAddress">
      <div>
        <van-address-list
          v-model="chosenAddressId"
          :list="addressList"
          default-tag-text="默认"
          @edit="handleEdit"
          @add="handleAdd"

        />
      </div>
    </van-popup>

    <van-popup v-model="showSetPassword" position="bottom" closeable round :style="{ height:'60%' }" @close="setPassword = ''">
      <div class="setPassTitle"><h3>设置您的支付密码</h3></div>
      <van-password-input
        :value="setPassword"
        :focused="showSetPassword"
        @focus="showSetPassword = true"
        :length="6"
      />
      <van-number-keyboard
      maxlength="6"
      v-model="setPassword"
      :show="showSetPassword"
      @blur="showSetPassword = false"
      />
    </van-popup>
  </div>

</template>

<script>
import { getOrder, goPay, submit } from '@/api/pay'
import { checkPasswordSet, getAddressList, setPassword } from '@/api/user'
import loginConfirm from '@/mixins/loginConfirm'

export default {
  name: 'PayIndex',
  mixins: [loginConfirm],
  data () {
    return {
      tips: '',
      item: {},
      orderList: [],
      balance: 0,
      address: {},
      totalPrice: 0,
      totalCount: 0,
      showKeyboard: false,
      radio: '1',
      orderId: '',
      passwordNums: [1, 2, 3, 4, 5, 6],
      keys: [1, 2, 3, 4, 5, 6, 7, 8, 9, '', 0],
      passwordInput: '',
      addressList: [],
      showAddress: false,
      chosenAddressId: 1,
      showSetPassword: false,
      setPassword: ''
    }
  },
  methods: {
    async getOrderList () {
      if (await this.loginConfirm()) {
        return
      }
      const res = await getOrder(this.$store.getters.userId, this.cartIds, this.mode, this.quantity)
      this.orderList = res.data.orderListItems
      this.balance = res.data.balance
      this.address = res.data.address
      this.totalPrice = res.data.totalPrice
      this.totalCount = res.data.orderListItems.reduce((sum, item) => sum + item.quantity, 0)
      this.item = res.data

      if (res.data.address === null) {
        return
      }
      this.address = {
        address: res.data.address.province + '/' + res.data.address.city + '/' + res.data.address.district + '/' + res.data.address.street,
        detail: res.data.address.detail,
        id: res.data.address.id,
        isDefault: true,
        name: res.data.address.name,
        tel: res.data.address.phone
      }
    },
    async submit () {
      if (!await this.checkPasswordSet()) {
        this.$toast({
          message: '您还未设置支付密码,请先设置支付密码',
          position: 'top'
        })
        this.showSetPassword = true
        return
      }
      if (this.item.address === null) {
        this.$toast('请先选择配送地址')
        return
      }
      if (await this.loginConfirm()) {
        return
      }
      this.item.address = this.trans(this.address)
      const res = await submit(this.item, 'BALANCE', this.tips, this.cartIds)
      this.orderId = res.data
      this.showKeyboard = true
    },
    trans (address) {
      const addressParts = address.address.split('/')
      return {
        province: addressParts[0],
        city: addressParts[1],
        district: addressParts[2],
        street: addressParts[3],
        detail: address.detail,
        name: address.name,
        phone: address.phone,
        id: address.id
      }
    },
    inputPay (num) {
      if (this.passwordInput.length === this.passwordNums.length) {
        return
      }
      this.passwordInput = this.passwordInput + num.toString()
      if (this.passwordInput.length === this.passwordNums.length) {
        this.goPay()
      }
    },
    delPay () {
      if (this.passwordInput.length === 0) {
        return
      }
      this.passwordInput = this.passwordInput.substring(0, this.passwordInput.length - 1)
    },
    async goPay () {
      if (await this.loginConfirm()) {
        return
      }
      const res = await goPay(this.passwordInput, this.orderId)
      this.passwordInput = ''

      if (res.code === -5) {
        this.$toast('密码错误')
        return
      }
      if (res.code === -6) {
        this.$toast('余额不足')
        return
      }
      this.$toast.success('支付成功')
      this.$router.replace('/myorder?dataType=2')
    },
    async selectAddress () {
      const res = await getAddressList()
      this.addressList = res.data
      this.chosenAddressId = this.addressList === null ? 0 : this.addressList.find(obj => obj.isDefault === true).id
    },
    handleEdit (item) {
      this.$router.push(`/editaddress/${item.id}`)
    },
    handleAdd () {
      this.$router.push('/editAddress/0')
    },
    changeAddress () {
      this.address = this.addressList.find(obj => obj.id === this.chosenAddressId)
    },
    handleClose () {
      this.$router.replace('/myorder?dataType=1')
    },
    async setPasswordHandle (password) {
      await setPassword(password)
      this.$toast('设置成功')
      this.showSetPassword = false
    },
    async checkPasswordSet () {
      const res = await checkPasswordSet()
      return res.data
    }
  },
  created () {
    this.getOrderList()
  },
  computed: {
    mode () {
      return this.$route.query.mode
    },
    cartIds () {
      const cartIdsParam = this.$route.query.cartIds
      return Array.isArray(cartIdsParam) ? cartIdsParam : [cartIdsParam]
    },
    quantity () {
      return this.$route.query.quantity
    },
    longAddress () {
      return this.address.province + this.address.city + this.address.district + this.address.street + this.address.detail
    }
  },
  watch: {
    setPassword (value) {
      if (value.length === 6) {
        this.setPasswordHandle(value)
      }
    }
  }

}
</script>

<style lang="less" scoped>
.pay {
  padding-top: 46px;
  padding-bottom: 46px;
  ::v-deep {
    .van-nav-bar__arrow {
      color: #333;
    }
  }
}
.address {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding: 20px;
  font-size: 14px;
  color: #666;
  position: relative;
  background: url(@/assets/border-line.png) bottom repeat-x;
  background-size: 60px auto;
  .left-icon {
    margin-right: 20px;
  }
  .right-icon {
    position: absolute;
    right: 20px;
    top: 50%;
    transform: translateY(-7px);
  }
}
.goods-item {
  height: 100px;
  margin-bottom: 6px;
  padding: 10px;
  background-color: #fff;
  display: flex;
  .left {
    width: 100px;
    img {
      display: block;
      width: 80px;
      margin: 10px auto;
    }
  }
  .right {
    flex: 1;
    font-size: 14px;
    line-height: 1.3;
    padding: 10px;
    padding-right: 0px;
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    color: #333;
    .info {
      margin-top: 5px;
      display: flex;
      justify-content: space-between;
      .price {
        color: #fa2209;
      }
    }
  }
}

.flow-num-box {
  display: flex;
  justify-content: flex-end;
  padding: 10px 10px;
  font-size: 14px;
  border-bottom: 1px solid #efefef;
  .money {
    color: #fa2209;
  }
}

.pay-cell {
  font-size: 14px;
  padding: 10px 12px;
  color: #333;
  display: flex;
  justify-content: space-between;
  .red {
    color: #fa2209;
  }
}
.pay-detail {
  border-bottom: 1px solid #efefef;
}

.pay-way {
  font-size: 14px;
  padding: 10px 12px;
  border-bottom: 1px solid #efefef;
  color: #333;
  .tit {
    line-height: 30px;
  }
  .pay-cell {
    padding: 10px 0;
  }
  .van-icon {
    font-size: 20px;
    margin-right: 5px;
  }
}

.buytips {
  display: block;
  textarea {
    display: block;
    width: 100%;
    border: none;
    font-size: 14px;
    padding: 12px;
    height: 100px;
  }
}

.footer-fixed {
  position: fixed;
  background-color: #fff;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 46px;
  line-height: 46px;
  border-top: 1px solid #efefef;
  font-size: 14px;
  display: flex;
  .left {
    flex: 1;
    padding-left: 12px;
    color: #666;
    span {
      color:#fa2209;
    }
  }
  .tipsbtn {
    width: 121px;
    background: linear-gradient(90deg,#f9211c,#ff6335);
    color: #fff;
    text-align: center;
    line-height: 46px;
    display: block;
    font-size: 14px;

  }
}
.top_pay {
  margin-top: 15px;
  text-align: center;
}
.top_pay h3 {
  font-size: 14px;
}
.top_pay span {
  display: block;
  font-size: 40px;
  font-weight: 600;
  margin-top: 10px;
}

.account_pay {
  display: flex;
  justify-content: space-between;
  margin: 20px 15px 15px 15px;
  font-size: 14px;
}

.pay_methods {
  padding: 15px;
  height: 100px;
}

.pay_methods .van-cell {
  background-color: #ededed;
}

.footer_pay {
  width: 375px;
}
.pay_input {
  display: flex;
  padding: 10px;
  justify-content: space-between;
}

.input_item {
  width: 45px;
  height: 45px;
  background-color: #e5e5e6;
  border-radius: 5px;
  text-align: center;
  line-height: 55px;
  font-size: 30px;
}
.keyboard_pay {
  margin: 20px;
}
.keyboard_pay ul{
  display: flex;
  flex-wrap: wrap;
}

.keyboard_pay li {
  display: block;
  width: 33%;
  border: #e5e5e6 0.1px solid;
  text-align: center;
  padding: 18px;
  font-size: 20px;
}

.setPassTitle {
  text-align: center;
  font-size: 17px;
  font-weight: 500;
  margin-top: 20px;
  margin-bottom: 10px;
}
</style>
